package p2p.simulation;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import p2p.logic.connection.client.Client;
import p2p.peer.Peer;

public class Simulation {
	
	private Set<Integer> ports;
	private Random random;
	private boolean isRunning;
	
	private static Simulation simulation;
	
	private Simulation(){
		this.ports = new HashSet<Integer>();
		this.random = new Random(System.currentTimeMillis());
	}
	
	public static Simulation getInstance(){
		if (simulation == null)
			simulation = new Simulation();
		return simulation;
	}
	
	public void start(){
		
		isRunning = true;
		
		Peer peer = new Peer(getOpenPort());
		peer.listen();
		PeerManager.getInstance().addPeerAndSimulate(peer);
		
	}
	
	public void stop(){
		
		isRunning = false;
	
	}
	
	public synchronized Integer getOpenPort(){
		
		int port = (Math.abs(random.nextInt()) % 5000) + 50000;
		
		if (ports.contains(port))
			return getOpenPort();
		else{
			
			this.ports.add(port);
			return port;
		
		}
	}

	public synchronized boolean isRunning() {
		if (!isRunning)
			return false;
		
		if (this.ports.size() > 2)
			return false;
		
		return true;
	}
	
	public void setIsRunning(boolean isRunning){
		this.isRunning = false;
	}
	

}
